package com.xjw.weixin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xjw.process.WechatProcess;
import com.xjw.util.SignUtil;

public class TestServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 微信加密签名  
        String signature = request.getParameter("signature");  
        // 时间戳  
        String timestamp = request.getParameter("timestamp");  
        // 随机数  
        String nonce = request.getParameter("nonce");  
        // 随机字符串  
        String echostr = request.getParameter("echostr");  
        OutputStream out = response.getOutputStream();
        //是否是第一次校验逻辑,只有第一次访问的时候，才会有echostr内容
        if (null != echostr && !"".equals(echostr)) {
	        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
	        if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
	            out.write(echostr.getBytes());  
	        }  
		}else{
			StringBuffer sb = new StringBuffer();
			InputStream is = request.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(isr);
			String s = "";
			while ((s = br.readLine()) != null) {
				sb.append(s);
			}
			String xml = sb.toString();	//次即为接收到微信端发送过来的xml数据
			System.out.println("receiveMessage:" + xml);
			WechatProcess process = new WechatProcess();
			String resultXml = process.processWechatMag(xml);
			out.write(resultXml.getBytes("UTF-8"));	
		}

      
        out.flush();
        out.close();
	}
}
